<template>
  <view class="container">
    <!-- 头部信息 -->
    <view class="header">
      <view class="header_top">
        <view class="title" @click="openPicker"> {{selectedValue||'请选择药仓'}}</view>
        <image src="/static/index/groups2.png" mode="widthFix" class="active-line-img"></image>
      </view>
      <uv-picker ref="picker" :columns="columns" @confirm="confirm"></uv-picker>
      <view class="status">
        设备编号：{{machineInfo.serialNumber||'-'}}
        <text class="status-tag online">{{machineInfo.status == 1 ? '在线' : '离线'}}</text>
        <text class="status-tag restart" @click="handleRestart">
          <image src="/static/index/icon_12.png" mode="widthFix" class="second-icon" />重启
        </text>
      </view>
      <view class="notification" @click="handleMessage">
        <image src="/static/index/icon_10.png" mode="widthFix" class="sound-icon"></image>
        <uv-notice-bar :text="noticeList" :icon="false" bgColor="transparent" color="#000" size="16"
          direction="column"></uv-notice-bar>
      </view>
    </view>

    <!-- 工作台 -->
    <view class="workbench">
      <view class="workbench-header">
        <text>工作台</text>
        <text class="date">{{getCurrentTime()}}</text>
        <view class="refresh" @click="refreshI()">
          <image src="/static/index/icon_11.png" mode="widthFix"></image>
          刷新
        </view>
      </view>

      <!-- 温湿度信息 -->
      <view class="env-info">
        <view class="temp-item" @click="handleTem()" :class="{'active2':isTemperature}">
          <text class="value">{{machineInfo.temperature||0}}℃</text>
          <view class="label">
            <view>
              <image src="/static/index/icon_9.png" mode="widthFix"></image>
            </view>
            <view>
              温度
            </view>
          </view>
        </view>
        <view class="temp-item" @click="handleTem()" :class="{'active2':isHumidity}">
          <text class="value">{{machineInfo.humidity||0}}%rh</text>
          <view class="label">
            <view>
              <image src="/static/index/icon_8.png" mode="widthFix"></image>
            </view>
            <view>
              湿度
            </view>
          </view>
        </view>
      </view>

      <!-- 运行统计 -->
      <view class="stats">
        <view class="stat-item" @click="handleOrderList()">
          <text class="label">历史运行</text>
          <text class="number">{{runInfo.total||0}}</text>

        </view>
        <view class="stat-item" @click="handleOrderList(2)">
          <text class="label">今日运行</text>
          <text class="number">{{runInfo.todayTotal||0}}</text>

        </view>
        <view class="stat-item" @click="handleOrderList(3)">
          <text class="label">今日异常</text>
          <text class="number warning">{{runInfo.todayAbnormal||0}}</text>
        </view>
      </view>
    </view>

    <!-- 快捷入口 -->
    <view class="shortcuts">
      <view class="shortcuts-header">
        <text>快捷入口</text>
        <view class="more" @click="handleOrderList()">
          <view>订单列表</view>
          <view class="time-arrow">
            <image src="/static/index/arrow.png" mode="aspectFit" />
          </view>
        </view>
      </view>
      <view class="shortcut-grid">
        <view class="grid-item" v-for="(item, index) in shortcutList" :key="index" @click="handleShortcut(item)">
          <view class="grid-item-icon">
            <image :src="item.icon" mode="widthFix"></image>
          </view>
          <text>{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <tab-bar></tab-bar>
  </view>
</template>

<script setup>
  import {
    ref
  } from 'vue'
  import {
    getcabinetInfo,
    getcabinetList,
    getMessageList,
    getorderStatistics,
    restart,
    getHeartbeat
  } from "@/api/index.js"
  import {
    useUserStore
  } from "@/stores/user.js"
  import {
    onShow
  } from "@dcloudio/uni-app";
  import {
    getCurrentTime
  } from "@/utils/mothed.js"
  import {
    storeToRefs
  } from 'pinia'
  import TabBar from '@/components/TabBar/index.vue'
  const userStore = useUserStore()
  const {
    userInfo
  } = storeToRefs(userStore)
  const machineInfo = ref({})
  const isTemperature = ref(false)
  const isHumidity = ref(false)
  const noticeList = ref([])
  const picker = ref(null)
  const machineList = ref([])
  const columns = ref([
    []
  ])
  const selectedValue = ref('')
  const runInfo = ref({})
  const selectedMachine = ref({})
  // 快捷入口列表
  const shortcutList = ref([{
    id: 1,
    name: '操作说明',
    icon: '/static/index/icon_1.png',
    path: '/pages/operate/index'
  },
  {
    id: 2,
    name: '库存管理',
    icon: '/static/index/icon_2.png',
    path: '/pages/storeManage/index'
  },
  {
    id: 3,
    name: '线下出药',
    icon: '/static/index/icon_3.png',
    path: '/pages/storeManage/offline'
  },
  {
    id: 4,
    name: '货道设置',
    icon: '/static/index/icon_4.png',
    path: '/pages/channel/index'
  },
  {
    id: 5,
    name: '查询统计',
    icon: '/static/index/icon_5.png',
    path: '/pages/order/index'
  },
  {
    id: 6,
    name: '故障申报',
    icon: '/static/index/icon_6.png',
    path: '/pages/broken/apply'
  },
  {
    id: 7,
    name: '温湿度汇总',
    icon: '/static/index/icon_7.png',
    path: '/pages/index/temperature'
  }
  ])
  const storeId = ref('')

  const openPicker = () => {
    picker.value.open()
  }

  const confirm = (e) => {
    // 获取选中的药仓数据
    selectedMachine.value = machineList.value[e.indexs[0]]
    selectedValue.value = selectedMachine.value.name
    uni.setStorageSync('selectedInfo', selectedMachine.value)
    // 如果需要根据选中的药仓加载对应的数据
    refreshInfo()
  }
  const refreshI = () => {
    if (!selectedMachine.value.id) {
      uni.showToast({
        title: '请先选择药仓！',
        icon: 'error'
      })
      return
    }
    uni.showToast({
      title: '刷新中...',
      icon: 'loading',
      duration: 500
    })

    let id = selectedMachine.value?.id
    getHeartbeat(id).then(res => {
      if (res.code == 200) {
        machineInfo.temperature = res.data.temperature
        machineInfo.humidity = res.data.humidity
        uni.showToast({
          title: res.msg,
          icon: 'success'
        })
      }
      // refreshInfo()
    })
  }
  const refreshInfo = () => {
    if (!selectedMachine.value?.id) return
    cabinetInfo(selectedMachine.value?.id)
    orderStatistics(selectedMachine.value?.id)
    setTimeout(() => {
      uni.hideLoading()
    }, 500)
  }
  // 处理快捷入口点击
  const handleShortcut = (item) => {
    if (item.path.includes('order')) {
      uni.navigateTo({
        url: item.path + '?id=' + selectedMachine.value.id + '&name=' + item.name
      })
    } else {
      if (item.id != 1) {
        if (!selectedMachine.value || !selectedMachine.value.id) {
          uni.showToast({
            title: '请先选择药仓！',
            icon: 'error'
          })
          return
        }
      }
      uni.navigateTo({
        url: item.path
      })
    }
  }

  const handleOrderList = (status) => {
    uni.navigateTo({
      url: `/pages/order/index?id=${selectedMachine.value.id}&name=订单列表&status=${status || ''}`
    })
  }

  const handleTem = () => {
    if (!selectedMachine.value || !selectedMachine.value.id) {
      uni.showToast({
        title: '请先选择药仓！',
        icon: 'error'
      })
      return
    }
    uni.navigateTo({
      url: '/pages/index/temperature'
    })
  }
  const handleMessage = () => {
    uni.navigateTo({
      url: '/pages/index/message'
    })
  }

  //柜机列表
  const cabinetList = () => {
    console.log(userInfo.value.storeId, !userInfo.value?.storeId)
    if (!userInfo.value?.storeId) return

    storeId.value = userInfo.value.storeId
    machineList.value = []
    columns.value[0] = []
    getcabinetList({
      storeId: storeId.value
    }).then(res => {
      machineList.value = res.data
      res.data.map(item => {
        item.name ? columns.value[0].push(item.name) : columns.value[0].push('-')
      })
      selectedMachine.value = uni.getStorageSync('selectedInfo') || res.data[0]
      selectedValue.value = selectedMachine.value.name
      refreshInfo()
    })
  }

  //柜机信息
  const cabinetInfo = (id) => {
    getcabinetInfo(id).then(res => {
      const {
        heartbeat,
        temperatureMax,
        temperatureMin,
        humidityMax,
        humidityMin,
        id
      } = res.data
      machineInfo.value = heartbeat || {}
      machineInfo.value.serialNumber = res.data.serialNumber || ''
      machineInfo.value.cabinetId = res.data.id || ''
      const temperature = Number(machineInfo.value.temperature)
      const humidity = Number(machineInfo.value.humidity)

      isTemperature.value = temperature >= Number(temperatureMin) && temperature <= Number(
        temperatureMax)
      isHumidity.value = humidity >= Number(humidityMin) && humidity <= Number(humidityMax)
      console.log(temperature, '温度', temperatureMin, temperatureMax, isTemperature.value)
      console.log(humidity, '湿度', humidityMin, humidityMax, isHumidity.value)
      uni.setStorageSync('machineInfo', res.data)
    })
  }

  //运行统计
  const orderStatistics = (id) => {
    getorderStatistics(id).then(res => {
      runInfo.value = res.data || {}
    })
  }

  //获取消息列表
  const messageList = () => {
    getMessageList().then(res => {
      console.log(res.rows, '-----333----')
      if (res.rows && res.rows.length > 0) {
        res.rows.map(item => {
          noticeList.value.push(item.title + '：' + item.content)
        })
      } else {
        noticeList.value = ['设备运行正常，无异常通知']
      }
    })
  }

  // 重启柜机
  const handleRestart = () => {
    uni.showModal({
      title: '提示',
      content: '确定要重启柜机吗？',
      success: (res) => {
        if (res.confirm) {
          restart(selectedMachine.value.id).then(res => {
            uni.showToast({
              title: '重启指令已发送',
              icon: 'success'
            })
          })
        }
      }
    })
  }

  onShow(() => {
    selectedMachine.value = uni.getStorageSync('selectedInfo') || {}
    cabinetList()
    messageList()
  })
</script>

<style lang="scss" scoped>
  .container {
    min-height: 100vh;
    background-color: #fff;
    position: relative;
    overflow: hidden;
  }

  .time-arrow {
    margin-left: 10rpx;

    image {
      width: 18rpx;
      height: 20rpx;
    }
  }

  .header {
    background-image: url('/static/index/bg.png');
    background-size: 100% 100%;
    background-position: center top;
    background-repeat: no-repeat;
    padding: 120rpx 30rpx 40rpx;

    color: #fff;
    height: 100vh;
    box-sizing: border-box;

    .header_top {
      display: flex;
      align-items: center;
    }

    .active-line-img {
      width: 16rpx;
      height: 16rpx;
      line-height: 16rpx;
      margin-left: 18rpx;
      transform: rotate(0deg);
      transition: transform 0.5s ease;
      margin-bottom: 16rpx;
    }

    .active {
      .active-line-img {
        transform: rotate(180deg);
      }
    }

    .time {
      font-size: 32rpx;
      margin-bottom: 20rpx;
    }

    ::v-deep .uv-notice-bar {
      padding: 0;
    }



    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #374151;
      margin-bottom: 20rpx;
      /* 超出隐藏 */
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .status {
      font-size: 28rpx;
      margin-bottom: 30rpx;
      color: #374151;

      .status-tag {
        margin-left: 20rpx;
        padding: 6rpx 16rpx 6rpx;
        border-radius: 20rpx;
        font-size: 24rpx;

        &.online {
          background-color: #4CAF50;
          color: #fff;
          padding: 6rpx 20rpx 6rpx;
        }

        &.restart {
          background-color: #E84444;
          color: #fff;
        }

        .second-icon {
          margin-top: 2rpx;
          width: 20rpx;
          height: 20rpx;
          margin-right: 6rpx;
        }
      }
    }

    .notification {
      display: flex;
      align-items: center;
      background: linear-gradient(to right, #D4EFF6, #fff);
      padding: 16rpx 26rpx;
      border-radius: 40rpx;
      margin-top: 30rpx;
      font-family: Roboto-Regular;
      box-shadow: 0 0px 2rpx 2rpx #fff;
      color: #333333;

      .sound-icon {
        width: 28rpx;
        height: 25rpx;
        margin-right: 10rpx;
      }
    }
  }

  .workbench {
    margin: 28rpx;
    box-shadow: 0 0px 2rpx 2rpx #fff;
    background-color: rgba(250, 246, 246, 0.171);
    border-radius: 16rpx;
    padding: 20rpx 30rpx;
    position: absolute;
    top: 19%;
    width: 85%;

    &-header {
      display: flex;
      align-items: center;
      margin-bottom: 24rpx;
      font-size: 34rpx;
      font-weight: bold;
      color: #333;

      .date {
        margin: 10rpx 20rpx 0;
        color: #9CA3AF;
        font-size: 26rpx;
        font-weight: normal;
      }

      .refresh {
        margin-left: auto;
        display: flex;
        align-items: center;
        color: #4CAF50;
        font-size: 28rpx;
        font-weight: normal;

        image {
          width: 32rpx;
          height: 32rpx;
          margin-right: 8rpx;
        }
      }
    }
  }

  .env-info {
    display: flex;
    margin-bottom: 24rpx;
    border-radius: 12rpx;

    .temp-item {
      flex: 1;
      display: flex;
      padding: 14px;
      flex-direction: column;
      margin-right: 20px;
      align-items: left;
      position: relative;
      border-radius: 10px;
      background: linear-gradient(to right, #FF0202, #FD5000);

      &:last-child {
        margin-right: 0;
      }



      .value {
        font-size: 46rpx;
        font-weight: bold;
        color: #fff;
        line-height: 1;
        margin-bottom: 12rpx;
      }

      .label {
        font-size: 24rpx;
        color: #fff;
        display: flex;
        align-items: center;
      }
    }

    image {
      margin-top: 3rpx;
      width: 28rpx;
      height: 28rpx;
      margin-right: 8rpx;
    }
  }

  .active2 {
    background: linear-gradient(to right, #02BFFF, #0090FD) !important;
  }

  .stats {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;

    .stat-item {
      flex: 1;
      text-align: left;
      position: relative;
      background-color: #F9FAFB;
      margin-right: 16px;
      border-radius: 10px;
      padding: 6px 12px;

      &:last-child {
        margin-right: 0;
      }

      .number {
        display: block;
        font-size: 32rpx;
        color: #2196F3;
        margin-top: 10rpx;
        font-weight: 500;

        &.warning {
          color: #E84444;
        }
      }

      .label {
        font-size: 28rpx;
        color: #6B7280;
        margin-bottom: 2px;
      }
    }
  }

  .shortcuts {
    margin: 12px 28rpx 14px;
    background-color: rgba(250, 246, 246, 0.192);
    border-radius: 16rpx;
    padding: 20rpx 30rpx;
    position: absolute;
    top: 46.5%;
    width: 85%;
    box-shadow: 0 0px 2rpx 2rpx #fff;

    &-header {
      display: flex;
      font-weight: 600;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      font-size: 32rpx;

      .more {
        color: #434444;
        font-size: 28rpx;
        font-weight: 400;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }

  .shortcut-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 26rpx;

    .grid-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .grid-item-icon {
        padding: 8px 0;
        border-radius: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 86rpx;
        height: 76rpx;
      }

      image {
        width: 86rpx;
        height: 76rpx;
      }

      text {
        font-size: 24rpx;
        color: #000;
        text-align: center;
        line-height: 1.4;
        white-space: nowrap;
      }
    }
  }
</style>